package v1

import (
	"RoccBlog/global"
	"RoccBlog/model"
	"RoccBlog/util"
)

type GeneratorRepository struct {
}

func (r *GeneratorRepository) Create(data model.GeneratorTable) error {
	return global.DB.Create(&data).Error
}

func (r *GeneratorRepository) Delete(id int) error {
	db := global.DB.Begin()

	err := db.Model(&model.GeneratorTable{Id: id}).Association("GeneratorColumns").Clear()
	if err != nil {
		db.Rollback()
		return err
	}

	err = db.Delete(&model.GeneratorTable{}, id).Error
	if err != nil {
		db.Rollback()
		return err
	}
	db.Commit()
	return nil
}

func (r *GeneratorRepository) Update(data model.GeneratorTable) error {
	return global.DB.Model(&data).Updates(&data).Error
}

func (r *GeneratorRepository) Select(pageNum, pageSize int) (any, error) {
	var list []model.GeneratorTable
	var count int64
	var err error
	db := global.DB.Model(&model.GeneratorTable{})

	if err = db.Count(&count).Error; err != nil {
		return nil, err
	}

	err = db.Offset((pageNum - 1) * pageSize).Limit(pageSize).Find(&list).Error
	return util.ToPageInfo(count, pageSize, pageNum, list), err
}

func (r *GeneratorRepository) SelectById(id int) (model.GeneratorTable, error) {
	var generatorTable model.GeneratorTable
	err := global.DB.Preload("GeneratorColumns").Take(&generatorTable, id).Error
	return generatorTable, err
}

// UpdateGeneratorTableColumns 更新生成字段信息
func (r *GeneratorRepository) UpdateGeneratorTableColumns(generatorTableId int, columns []model.GeneratorColumn) error {
	global.DB.Exec("delete from generator_column where  generator_table_id = ?", generatorTableId)
	return global.DB.Model(&model.GeneratorTable{Id: generatorTableId}).Association("GeneratorColumns").Append(columns)
}
